package com.wx.disparent.mallparent.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.wx.disparent.mallparent.commons.util.PageResult;
import com.wx.disparent.mallparent.entity.*;
import com.wx.disparent.mallparent.service.OrderService;
import com.wx.disparent.mallparent.service.ParaService;
import com.wx.disparent.mallparent.service.ProductService;
import com.wx.disparent.mallparent.service.UserService;
import org.apache.catalina.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 曾右权
 * @description
 * @date 2019/12/11 9:34
 */
@RestController
@RequestMapping("/front/orderPhone")
public class OderPhoneController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ParaService paraService;
    @Autowired
    private UserService userService;

    /**
     * 跳转到提交订单页面
     *
     * @param productId 商品id
     * @param totalNum  购买数量
     * @return ModelAndView
     */
    @RequestMapping("/orderGenerate")
    public ModelAndView ordergenerate(@RequestParam(value = "productId") Integer productId, @RequestParam(value = "totalNum") Integer totalNum) {
        ModelAndView model = new ModelAndView();
        Map<String, Object> map = orderService.ordergenerate(productId, totalNum);
        model.addObject("order", (OrderEntity) map.get("order"));
        model.addObject("product", (ProductEntity) map.get("product"));
        model.setViewName("web/orderGenerate");
        return model;
    }

    /**
     * 提交订单
     * @param orderEntity 订单信息
     * @return 执行结果 0失败
     */
    @RequestMapping("/orderCommit")
    public Map orderCommit(OrderEntity orderEntity) {
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> map2 = new HashMap<>();
        map2.put("userId",orderEntity.getUserId());
        map.put("result",orderService.insert(orderEntity));
//        System.out.println("*(***************"+orderService.findAll(map2).get(0).getId());
        map.put("orderId",orderService.findAll(map2).get(0).getId());
        return map;
    }

    /**
     * 查询上级用户账号
     * @param referId
     * @return 执行结果 0失败
     */
    @RequestMapping("/chooseAcctType")
    public ModelAndView chooseAcctType(@RequestParam(value = "orderId") Integer orderId,@RequestParam(value = "referId") Integer referId) {
        OrderEntity orderEntity = orderService.findById(orderId);
        UserEntity userEntity = orderService.findReferAccout(referId);
        ModelAndView mv = new ModelAndView();
        mv.addObject("userEntity",userEntity);
        mv.addObject("orderEntity",orderEntity);
        mv.setViewName("web/orderGeneratePay");
        return mv;
    }

    /**
     * 查询商家账号
     * @param orderId
     * @return 执行结果 0失败
     */
    @RequestMapping("/findMerchantEntityAccout")
    public ModelAndView findMerchantEntityAccout(@RequestParam(value = "orderId") Integer orderId,@RequestParam(value = "productId") Integer productId) {
        OrderEntity orderEntity = orderService.findById(orderId);
        MerchantEntity merchantEntity = orderService.findMerchantEntityAccout(productId);
        ModelAndView mv = new ModelAndView();
        mv.addObject("merchantEntity",merchantEntity);
        mv.addObject("orderEntity",orderEntity);
        mv.setViewName("web/referOrderGeneratePay");
        return mv;
    }

    /**
     * 跳转到等待上级用户确认
     * @param orderId 订单信息
     * @return 执行结果 0失败
     */
    @RequestMapping("/afterPay")
    public ModelAndView afterPay(@RequestParam(value = "orderId") Integer orderId) {
        ModelAndView modelAndView = new ModelAndView();
        OrderEntity orderEntity = orderService.findById(orderId);
        orderService.update(orderEntity,4);
        modelAndView.addObject("orderId",orderId);
        modelAndView.setViewName("web/afterPay");
        return modelAndView;
    }

    /**
     * 跳转到等待商家户确认
     * @param orderId 订单信息
     * @return 执行结果 0失败
     */
    @RequestMapping("/referAfterPay")
    public ModelAndView referAfterPay(@RequestParam(value = "orderId") Integer orderId) {
        ModelAndView modelAndView = new ModelAndView();
        OrderEntity orderEntity = orderService.findById(orderId);
        orderService.update(orderEntity,5);
        modelAndView.addObject("orderId",orderId);
        modelAndView.setViewName("web/referAfterPay");
        return modelAndView;
    }

    /**
     * 跳转到选择支付方式页面
     * @param orderId 订单信息
     * @return 执行结果 0失败
     */
    @RequestMapping("/orderGeneratePay")
    public ModelAndView orderGeneratePay(@RequestParam(value = "orderId") Integer orderId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("orderId",orderId);
        modelAndView.setViewName("web/orderGeneratePay");
        return modelAndView;
    }

    /**
     * 查询我的最近一条订单
     *
     * @param userId 用户id
     * @return 订单集合
     */
    @RequestMapping("/getAllByUserIdAndType")
    public ModelAndView getAllByUserId(@RequestParam(value = "userId") String userId, @RequestParam(value = "type") String type) {
//        System.out.println(userId);
        ModelAndView model = new ModelAndView();
        Map<String, Object> paramMap = new HashMap<String, Object>();
//        获取用户id
        if (userId != null && !userId.equals("")) {
            paramMap.put("userId", userId);
            List<OrderEntity> all = orderService.findAll(paramMap);
            if (type.equals("1")) {
                model.addObject("orders", all.get(0));
                model.setViewName("web/orderInfos");
            } else {
                model.addObject("orders", all);
                model.setViewName("web/orderInfos");
            }
        } else {
            model.setViewName("web/login");
        }
        return model;
    }

    /**
     * 查询我的所有订单
     *
     * @param userId 用户id
     * @return 订单集合
     */
    @RequestMapping("/getAllByUserId")
    public ModelAndView getAllByUserId(@RequestParam(value = "userId") String userId) {
        ModelAndView model = new ModelAndView();
//        Map<String, Object> paramMap = new HashMap<String, Object>();
////        获取用户id
//        if (userId != null && !userId.equals("")) {
//            paramMap.put("userId", userId);
//            List<OrderEntity> all = orderService.findAll(paramMap);
//            model.addObject("orders", all);
            model.setViewName("web/orderInfos");
//        } else {
//            model.setViewName("web/login");
//        }
        return model;
    }


    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public ModelAndView findById(@RequestParam(value = "id") Integer id) {
        ModelAndView model = new ModelAndView();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        OrderEntity orderEntity = orderService.findById(id);
        model.addObject("order", orderEntity);
        model.setViewName("web/orderInfo");
        return model;
    }



    /**
     * 查询下级订单
     * @param referId 上级用户ID
     * @return 订单集合
     */
    @RequestMapping("/getAllByReferId")
    public ModelAndView getAllByReferId(@RequestParam(value = "referId") String referId) {
//        System.out.println(referId);
        ModelAndView model = new ModelAndView();
//        Map<String, Object> paramMap = new HashMap<String, Object>();
////        获取上级用户ID
//        if (referId != null && !referId.equals("")) {
//            paramMap.put("referId", referId);
//            List<OrderEntity> all = orderService.findAll(paramMap);
//            model.addObject("orders", all);
            model.setViewName("web/orderInfosSubordinateList");
//        } else {
//            model.setViewName(null);
//        }
        return model;
    }


    @RequestMapping("/findByReferId")
    public ModelAndView findByReferId(@RequestParam(value = "id") Integer id) {
        ModelAndView model = new ModelAndView();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        OrderEntity orderEntity = orderService.findById(id);
        model.addObject("order", orderEntity);
        model.setViewName("web/orderInfosSubordinate");
        return model;
    }


    /**
     * 确认收货
     *
     * @param orderEntity 订单信息
     * @return 执行结果 0失败
     */
    @RequestMapping("/orderConfirmReceipt")
    public String orderConfirmReceipt(OrderEntity orderEntity) {
        return "" + orderService.update(orderEntity, 1);
    }

    /**
     * 取消订单
     *
     * @param orderId 订单id
     * @return 执行结果 0失败
     */
    @RequestMapping("/orderCancel")
    public String orderCancel(@RequestParam(value = "id") Integer orderId) {
        return "" + orderService.deleteById(orderId);
    }

    /**
     * 确认用户支付
     *
     * @param orderEntity 订单信息
     * @return 执行结果 0失败
     */
    @RequestMapping("/orderConfirmUserPay")
    public String orderConfirmUserPay(OrderEntity orderEntity) {
        return "" + orderService.update(orderEntity, 2);
    }

    /**
     * 查询订单
     * @param orderId 订单id
     * @return 执行结果 0失败
     */
    @RequestMapping("/findOrderEntityByOrderId")
    public OrderEntity findOrderEntityByOrderId(Integer orderId) {
//        System.out.println(orderId);
        return orderService.findById(orderId);
    }

    /**
     * 获取我的所有订单信息 （分页查询）
     *
     * @return 商品集合
     */
    @RequestMapping("/pageTablePhone")
    public String pageTablePhone(@RequestParam("aoData") String aoData, HttpSession httpSession) {
        PageResult pr = new PageResult(aoData);
        String search = pr.getSearch();

        JSONArray jsonArray = new JSONArray();
        List<OrderEntity> entities;
        UserEntity userEntity = (UserEntity) httpSession.getAttribute("userEntity");

        Map<String, Object> map = new HashMap<>();
        map.put("userId", userEntity.getId());
        entities = orderService.findAll(map);

        for (Object obj : entities) {
            OrderEntity entity = (OrderEntity) obj;
            JSONObject jsonObject = new JSONObject();

            jsonObject.put("productName", entity.getProductEntityName());
            jsonObject.put("payMoney", entity.getPayMoney());
            jsonObject.put("totalNum", entity.getTotalNum());

            jsonObject.put("consignStatus", entity.getConsignStatus());
            jsonObject.put("createTime", entity.getCreateTime());
            jsonObject.put("id", entity.getId());
            jsonArray.add(jsonObject);
        }

        String json = "{\"sEcho\":" + (pr.getsEcho()+1) + ",\"iTotalRecords\":" + pr.getPage().getTotal() + ",\"iTotalDisplayRecords\":" + pr.getPage().getTotal() + ",\"aaData\":" + jsonArray.toString() + "}";
        return json;
    }

    /**
     * 获取我的下级订单信息 （分页查询）
     *
     * @return 商品集合
     */
    @RequestMapping("/referPageTable")
    public String referPageTable(@RequestParam("aoData") String aoData, HttpSession httpSession) {
        PageResult pr = new PageResult(aoData);
        String search = pr.getSearch();

        JSONArray jsonArray = new JSONArray();
        List<OrderEntity> entities;
        UserEntity userEntity = (UserEntity) httpSession.getAttribute("userEntity");

        Map<String, Object> map = new HashMap<>();
//        System.out.println(userEntity.getId());
        map.put("referId", userEntity.getId());
        entities = orderService.findAll(map);

        for (Object obj : entities) {
            OrderEntity entity = (OrderEntity) obj;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", entity.getId());
            jsonObject.put("productName", entity.getProductEntityName());
            jsonObject.put("payMoney", entity.getPayMoney());
            jsonObject.put("payStatus", entity.getPayStatus());
            jsonObject.put("option", entity.getId());
            jsonArray.add(jsonObject);
        }

        String json = "{\"sEcho\":" + (pr.getsEcho()+1) + ",\"iTotalRecords\":" + pr.getPage().getTotal() + ",\"iTotalDisplayRecords\":" + pr.getPage().getTotal() + ",\"aaData\":" + jsonArray.toString() + "}";
        return json;
    }


}
